package com.gtq.uhome.JWTInterceptor;

import com.gtq.uhome.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Enumeration;

@CrossOrigin
@RestController
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        System.out.println("method:" + request.getMethod());
        if (request.getMethod().equals("OPTIONS")) {
            System.out.println("in----------------");
            response.setHeader("Access-Control-Allow-Origin", "*");

            response.setHeader("Access-Control-Allow-Credentials", "true");

            response.setHeader("Access-Control-Allow-Methods", "*");

            response.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");

            response.setHeader("Access-Control-Expose-Headers", "*");


            response.setStatus(200);
            PrintWriter writer = response.getWriter();
            writer.write("200");
            writer.flush();
            writer.close();

        }
      /*  TODO
  如果代码中有该标识，说明在标识处有功能代码待编写，待实现的功能在说明中会简略说明。

        FIXME: + 说明：
  如果代码中有该标识，说明标识处代码需要修正，甚至代码是错误的，不能工作，需要修复，如何修正会在说明中简略说明。

eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIiLCJpZCI6bnVsbCwiZ…3dCJ9.USGwPAckheIGV58WEUeYnu8f1S3TvZ4rTlo-2u0OBNw
：*/
        // 需要工具类JWTUtil来解析前端的请求头: Authorization
        JWTUtil util = new JWTUtil();
        String jwt = request.getHeader("Authorization");
        System.out.println("Authorization值：" + jwt);
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String header = request.getHeader(name);
            System.out.println("请求头名：" + name + "---------请求头的值：" + header);
        }
        try {
            if (jwt == null) {
                System.out.println("请求头为空, 验证失败");
            } else {
                Claims c;
                c = util.parseJWT(jwt);
                // 通过Claim对象,可以获取在jwt中保存的特征(Map)
                System.out.println("id为" + c.get("userId") + "的用户已是登录状态");
                //返回true表示放行
                return true;
            }
            System.out.println("token解析错误，验证失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 当返回false的时候, 表示被拦截住,没法访问controller
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
